package resourecemanager

import (
	"context"
	"errors"

	"dev.ixmxm.top/rms/boot"
	"dev.ixmxm.top/rms/codes"
	"dev.ixmxm.top/rms/model"
	"dev.ixmxm.top/rms/utils/function"
	"dev.ixmxm.top/rms/utils/log"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewResourceManager(db *boot.MongoDB) *ResourceManager {
	rsm := &ResourceManager{db: db}
	return rsm
}

type ResourceManager struct {
	db           *boot.MongoDB
	SystemConfig *model.SystemConfig //系统配置(缓存),不可直接赋值保存，调用SaveSystemConfigToCache保存
}

// GetPicture 获得所有的图片资源
func (m *ResourceManager) GetResourcePicturesFromDB(ctx context.Context) ([]model.ResourcePicture, codes.Code) {

	dbRes, err := m.db.Collection(ctx, model.ResourcePicture{}.TableName()).Find(ctx, bson.D{})
	if err != nil {
		log.ErrorfWithContext(ctx, "get resource pictures from db error:%s", err.Error())
		return nil, codes.ErrDatabase.Wrap(err)
	}
	resourcePictures := make([]model.ResourcePicture, 0)
	if errBind := dbRes.All(ctx, &resourcePictures); errBind != nil {
		log.ErrorfWithContext(ctx, "bind resource pictures logs from db error:%s", errBind.Error())
		return nil, codes.ErrDatabase.Wrap(errBind)
	}
	return resourcePictures, nil
}

//添加图片资源到数据库
func (m *ResourceManager) SaveResourcePictureToDB(ctx context.Context, resourcePicture *model.ResourcePicture) codes.Code {
	//写入数据库
	dbRes := m.db.Collection(ctx, model.ResourcePicture{}.TableName()).FindOneAndReplace(ctx, bson.M{"tag": resourcePicture.Tag}, resourcePicture, &options.FindOneAndReplaceOptions{Upsert: function.BoolPtr(true)})
	if dbRes.Err() != nil && !errors.Is(dbRes.Err(), mongo.ErrNoDocuments) {
		log.ErrorfWithContext(ctx, "add robot type to db error:%s", dbRes.Err().Error())
		return codes.ErrDatabase.Wrap(dbRes.Err())
	}
	return nil
}
